package com.ochnas.volunteersignup.ui;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

import com.ochnas.volunteersignup.domain.Event;
import com.ochnas.volunteersignup.domain.Position;
import com.ochnas.volunteersignup.service.EventService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


public class GetPositionsService extends HttpServlet {
    WebApplicationContext spring;
    private static final long serialVersionUID = -2560989072138239258L;

    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
        spring = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EventService eventService = (EventService) spring.getBean("eventService");

        // No id specified - return a list of all events
        if (request.getRequestURI().endsWith("/") || request.getRequestURI().endsWith("positions")) {
            Document doc = DocumentFactory.getInstance().createDocument();
            Element root = doc.addElement("events");
            List<Event> events = eventService.findAllEvents();
            for (Event event : events) {
                root.addElement("event").addAttribute("ref", request.getRequestURL()+"/"+event.getId());
            }

            response.getOutputStream().println(doc.asXML());
        }

        // If an id was specified, look up that item
        else {
            String id = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1);
            List<Position> positions = eventService.findPositionsByEventId(Long.parseLong(id));
            Document xmlResponse = DocumentFactory.getInstance().createDocument();
            
            Element root = xmlResponse.addElement("positions");
            for (Position position : positions) {
				try {
					Document parser = DocumentHelper.parseText(position.toXml());
	            	Node pNode = parser.selectSingleNode("position");
	                root.add(pNode);
				} catch (DocumentException e) {
					throw new ServletException("Invalid parsing of xml.", e);
				}

            }
            response.setContentType("text/xml");
            response.getOutputStream().println(xmlResponse.asXML());
        }
    }
}
